﻿using System;
using BikeBouncer.BusinessLayer.Entities;
using Devv.Core.Crypto;
using Devv.Core.Utils;

namespace BikeBouncer.Site
{
	public class CookieManager
	{
		#region Address cookies

		public static String CurrentCity
		{
			get
			{
				String c = CookieUtil.GetCookie("CurrentCity");

				if (String.IsNullOrEmpty(c) || c.Length < 1)
				{
					return LocationManager.GetIPCity();
				}

				return c;
			}
			set
			{
				CookieUtil.SetCookie("CurrentCity", value, DateTime.Now.AddDays(180));
			}
		}

		public static String CurrentCountry
		{
			get
			{
				String c = CookieUtil.GetCookie("CurrentCountry");

				if (String.IsNullOrEmpty(c) || c.Length < 1)
				{
					return LocationManager.GetIPCountry();
				}

				return c;
			}
			set
			{
				CookieUtil.SetCookie("CurrentCountry", value, DateTime.Now.AddDays(180));
			}
		}

		#endregion

		#region User cookies

		public static User LoggedUser
		{
			get
			{
				String c = CookieUtil.GetCookie("LoggedUser");

				if (String.IsNullOrEmpty(c) || c.Length < 5)
				{
					return null;
				}

				try
				{
					c = Cipher.AESDecrypt(c, ConfigUtil.GetConfig("BikeBouncer.SecurityKeys.LoggedUser"), true);

					String[] arr = c.Split("|".ToCharArray());
					User user = new User(arr[0]);

					if (user.Id > 0 && user.PasswordHash == User.GetPasswordHash(arr[0], arr[1]))
					{
						return user;
					}

					return null;
				}
				catch
				{
					return null;
				}
			}
			set
			{
				if (value == null)
				{
					CookieUtil.SetCookie("LoggedUser", String.Empty, DateTime.MinValue);
					return;
				}

				String c = Cipher.AESEncrypt(value.Email + "|" + value.Password, ConfigUtil.GetConfig("BikeBouncer.SecurityKeys.LoggedUser"), true);
				CookieUtil.SetCookie("LoggedUser", c, DateTime.Now.AddDays(30));
			}
		}

		public static DateTime LoginBlockingDate
		{
			get
			{
				return CookieUtil.GetCookie("LoginBlockingDate", DateTime.MinValue);
			}
			set
			{
				if (value > DateTime.MinValue)
				{
					CookieUtil.SetCookie("LoginBlockingDate", value, DateTime.Now.AddDays(1));
				}
				else
				{
					CookieUtil.SetCookie("LoginBlockingDate", String.Empty);
				}
			}
		}

		#endregion
	}
}